const createAsyncThunk = (typePrefix, payloadCreator) => {
  //声明了三个类型字符串
  const pendingType = `${typePrefix}/pending`;// todo/add/pending
  const fulfilledType = `${typePrefix}/fulfilled`;//todo/add/fulfilled
  const rejectedType = `${typePrefix}/rejected`;// todo/add/rejected
  //声明了函数(异步的 action)
  const thunk = async (dispatch) => {
    dispatch({ type: pendingType });// {type: 'todo/add/pending'}
    try {
      //执行异步任务
      const payload = await payloadCreator();
      dispatch({ type: fulfilledType, payload });// {type: 'todo/add/fulfilled', payload: todo}
    } catch (error) {
      dispatch({ type: rejectedType, error: error.message });// {type: 'todo/add/rejected', todo: error.message}
    }
  };

  thunk.fulfilled = fulfilledType;
  thunk.rejected = rejectedType;
  thunk.pending = pendingType;

  return thunk;
};


const createSlice = (options) => {
  const { name, initialState, reducers, extraReducers } = options;

  const slice = {
    name,
    initialState,
    reducers,
    extraReducers: {},
  };

  const { actions } = reducers;

  const builder = {
    addCase: (actionType, reducer) => {
      if (typeof reducer === 'function') {
        slice.extraReducers[actionType] = reducer;
      } else if (actions[actionType]) {
        slice.extraReducers[actionType] = actions[actionType];
      } else {
        throw new Error(`Invalid reducer found for action type: ${actionType}`);
      }
      return builder;
    },
  };

  if (typeof extraReducers === 'function') {
    //调用 extraReducers
    extraReducers(builder);
  } else if (typeof extraReducers === 'object') {
    Object.entries(extraReducers).forEach(([actionType, reducer]) => {
      builder.addCase(actionType, reducer);
    });
  }

  return slice;
};

//GPT-4
const createAsyncThunk2 = (type, asyncFunction) => {
  const actionCreator = (...args) => async (dispatch, getState) => {
      dispatch({ type: `${type}/pending` });
      try {
          const response = await asyncFunction(...args);
          dispatch({ type: `${type}/fulfilled`, payload: response });
          return response;
      } catch (error) {
          dispatch({ type: `${type}/rejected`, error });
      }
  };

  actionCreator.pending = `${type}/pending`;
  actionCreator.fulfilled = `${type}/fulfilled`;
  actionCreator.rejected = `${type}/rejected`;

  return actionCreator;
};